package com.volcreate.inn.controller.admin;


import com.volcreate.inn.po.User;
import com.volcreate.inn.service.impl.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

/**
 * @author zxc
 * @version 0.0.1
 * @date 2020/8/18
 */
@Controller
@RequestMapping("/admin")
public class ALoginController {

    private static final String INDEX = "admin/index";
    private static final String REDIRECT_INDEX = "redirect:/admin";
    private static final String REDIRECT_LOGIN = "redirect:/admin/login";
    private static final String LOGIN = "admin/login";

    private final UserService userService;

    public ALoginController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping(value = {"", "/", "index"})
    public String loginPage(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user != null) {
            return INDEX;
        }
        return LOGIN;
    }

    @GetMapping("/register")
    public String registerPage() {
        return "admin/register";
    }


    @PostMapping("/register")
    public String register(User user) {
        userService.register(user);
        return REDIRECT_LOGIN;
    }


    @PostMapping("/login")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession session,
                        RedirectAttributes attributes) {
        User user = userService.checkUser(username, password);
        if (user != null) {
            user.setPassword(null);
            session.setAttribute("user", user);
            return "redirect:/index";
        } else {
            attributes.addFlashAttribute("message", "用户名或密码错误....");
            return "redirect:/admin/index";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        return "index";
    }

}
